import bundleManager from '@ohos.bundle.bundleManager';
import abilityAccessCtrl, { Permissions, PermissionRequestResult, Context } from '@ohos.abilityAccessCtrl';
import { BusinessError } from '@ohos.base';

export const permissions: Array<Permissions> = [
    'ohos.permission.CAMERA', // 相机
    'ohos.permission.MICROPHONE',// 麦克风
];

async function checkAccessToken(permission: Permissions): Promise<abilityAccessCtrl.GrantStatus> {
    let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager();
    let grantStatus: abilityAccessCtrl.GrantStatus = abilityAccessCtrl.GrantStatus.PERMISSION_DENIED;

    // 获取应用程序的accessTokenID
    let tokenId: number = 0;
    try {
        let bundleInfo: bundleManager.BundleInfo = await bundleManager.getBundleInfoForSelf(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION);
        let appInfo: bundleManager.ApplicationInfo = bundleInfo.appInfo;
        tokenId = appInfo.accessTokenId;
    } catch (error) {
        let err: BusinessError = error as BusinessError;
        console.error(`[camera test] Failed to get bundle info for self. Code is ${err.code}, message is ${err.message}`);
    }

    // 校验应用是否被授予权限
    try {
        grantStatus = await atManager.checkAccessToken(tokenId, permission);
    } catch (error) {
        let err: BusinessError = error as BusinessError;
        console.error(`[camera test] Failed to check access token. Code is ${err.code}, message is ${err.message}`);
    }

    return grantStatus;
}

/**
 * 检查是否已经授权
 * @param permission
 * @returns
 */
export async function checkPermissions(permissions: Array<Permissions>): Promise<boolean> {
    for (let i = 0; i < permissions.length; i++) {
        let grantStatus: abilityAccessCtrl.GrantStatus = await checkAccessToken(permissions[i]);
        if (!(grantStatus === abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED)) {
            return false;
        }
    }
    return true;
}

/**
 * 申请获取权限
 * @param permissions
 * @param context[
 *      UI: getContext(this) as Context
 *      UIAbility: this.context
 * ]
 */
export async function reqPermissionsFromUser(permissions: Array<Permissions>, context: Context): Promise<boolean>  {
    let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager();
    // requestPermissionsFromUser会判断权限的授权状态来决定是否唤起弹窗
    let data: PermissionRequestResult = await atManager.requestPermissionsFromUser(context, permissions);
    let grantStatus: Array<number> = data.authResults;
    let length: number = grantStatus.length;
    console.log("length: "+grantStatus.toString());
    for (let i = 0; i < length; i++) {
        console.log("result: "+grantStatus[i]);
        if (!(grantStatus[i] === 0)) {
            return false;
        }
    }
    return true;
}
